package com.jinly.ryder.monitor.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinly.ryder.monitor.service.ActuatorQueryService;
import com.jinly.ryder.monitor.service.model.ActuateMetric;
import com.jinly.ryder.monitor.service.model.ServiceStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class ActuatorQueryServiceImpl implements ActuatorQueryService, InitializingBean {

    private RestTemplate restTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(500);
        requestFactory.setReadTimeout(500);
        restTemplate = new RestTemplate(requestFactory);
    }

    @Override
    public ServiceStatus health(String host, Integer port) {
        String url = "http://" + host + ":" + port + "/actuator/health";
        JSONObject json = doGet(url);
        if (json != null && json.containsKey("status")) {
            return ServiceStatus.of(json.getString("status"));
        }
        return ServiceStatus.DOWN;
    }

    @Override
    public ServiceStatus serviceRegistry(String host, Integer port) {
        String url = "http://" + host + ":" + port + "/actuator/service-registry";
        JSONObject json = doGet(url);
        if (json != null && json.containsKey("body")) {
            return ServiceStatus.of(json.getString("body"));
        }
        return ServiceStatus.DOWN;
    }

    @Override
    public ActuateMetric metrics(String host, Integer port, String metricsKey) {
        String url = "http://" + host + ":" + port + "/actuator/metrics/" + metricsKey;
        JSONObject json = doGet(url);
        if (json != null) {
            return json.toJavaObject(ActuateMetric.class);
        }
        return null;
    }


    private JSONObject doGet(String url) {
        try {
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                String json = responseEntity.getBody();
                JSONObject jsonObject = new JSONObject();
                try {
                    if (!ObjectUtils.isEmpty(json)) {
                        jsonObject = JSON.parseObject(json);
                    }
                } catch (Exception e) {
                    jsonObject.put("body", json);
                }
                return jsonObject;
            } else {
                log.error("请求[{}]失败:{}-{}", url, responseEntity.getStatusCode(), responseEntity.getBody());
            }
        } catch (Exception e) {
            log.error("请求[{}]失败:{}", url, e.getMessage());
        }
        return null;
    }


}
